<template>
  <view class="my-listings-container">
    <!-- 头部统计 -->
    <view class="header-stats">
      <view class="stat-item">
        <text class="stat-number">{{ totalCount }}</text>
        <text class="stat-label">总发布</text>
      </view>
      <view class="stat-item">
        <text class="stat-number">{{ sellingCount }}</text>
        <text class="stat-label">已上架</text>
      </view>
      <view class="stat-item">
        <text class="stat-number">{{ draftCount }}</text>
        <text class="stat-label">待上架</text>
      </view>
      <view class="stat-item">
        <text class="stat-number">{{ offlineCount }}</text>
        <text class="stat-label">已下架</text>
      </view>
    </view>

    <!-- 状态筛选 -->
    <view class="status-filter">
      <view 
        v-for="(status, index) in statusOptions" 
        :key="index"
        class="status-tab"
        :class="{ active: selectedStatus === status.value }"
        @click="changeStatus(status.value)"
      >
        <text>{{ status.label }}</text>
      </view>
    </view>

    <!-- 列表区域 -->
    <scroll-view
      class="listings-scroll"
      scroll-y
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
      :enable-back-to-top="true"
      :scroll-with-animation="true"
      :enhanced="true"
      :bounces="true"
    >
      <view class="listings-list">
        <view 
          v-for="item in services" 
          :key="item.id"
          class="listing-item"
        >
          <view class="listing-header" @click="goToDetail(item.id)">
            <text class="company-name">{{ item.title || item.name }}</text>
            <view class="status-tags">
              <view class="status-tag" :class="getStatusClass(item.status)">
                {{ getStatusText(item) }}
              </view>
              <view v-if="item.audit_status" class="audit-tag" :class="getAuditStatusClass(item.audit_status)">
                {{ getAuditStatusText(item.audit_status) }}
              </view>
            </view>
          </view>
          
          <view class="listing-info" @click="goToDetail(item.id)">
            <view class="info-row">
              <text class="label">类型：</text>
              <text class="value">{{ item.category?.name || '本地服务' }}</text>
            </view>
            <view class="info-row">
              <text class="label">地区：</text>
              <text class="value">{{ formatLocation(item) }}</text>
            </view>
            <view class="info-row">
              <text class="label">发布时间：</text>
              <text class="value">{{ formatTime(item.created_at) }}</text>
            </view>
            <view v-if="item.audit_status === '待审核' && item.auto_publish_at" class="info-row">
              <text class="label">自动发布：</text>
              <text class="value auto-publish">{{ formatTime(item.auto_publish_at) }}</text>
            </view>
            <view v-if="item.audit_comment" class="info-row">
              <text class="label">审核备注：</text>
              <text class="value audit-comment">{{ item.audit_comment }}</text>
            </view>
          </view>
          
          <view class="listing-footer">
            <view class="price-section">
              <text v-if="item.price && item.price > 0" class="price">¥{{ formatPrice(item.price) }}</text>
              <text v-else-if="item.is_negotiable" class="price negotiable">面议</text>
              <text v-else class="price negotiable">面议</text>
              <!-- 审核拒绝提示 -->
              <text v-if="item.audit_status === 'REJECTED'" class="rejected-tip">
                审核未通过，请修改后重新提交
              </text>
            </view>
            
            <view class="action-buttons">
              <!-- 编辑按钮 - 对所有状态的商品都显示 -->
              <button 
                class="action-btn edit-btn" 
                @click="editService(item)"
              >
                编辑
              </button>
              <button 
                v-if="item.status === 'PUBLISHED'" 
                class="action-btn offline-btn" 
                @click="offlineService(item)"
              >
                下架
              </button>
              <button 
                v-if="item.status === 'OFFLINE'" 
                class="action-btn online-btn" 
                @click="republishService(item)"
              >
                重新上架
              </button>
              <button 
                v-if="item.status === 'DRAFT' || item.status === 'OFFLINE'" 
                class="action-btn delete-btn" 
                @click="deleteService(item)"
              >
                删除
              </button>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 加载状态 -->
      <view class="loading-section" v-if="isLoading">
        <text class="loading-text">加载中...</text>
      </view>
      
      <!-- 没有更多数据 -->
      <view class="no-more-section" v-if="!hasMore && services.length > 0">
        <text class="no-more-text">没有更多数据了</text>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-section" v-if="!isLoading && services.length === 0">
        <text class="empty-text">暂无发布记录</text>
        <button class="publish-btn" @click="goToPublish">立即发布</button>
      </view>
    </scroll-view>

    <!-- 悬浮发布按钮 -->
    <view class="fab" @click="goToPublish">
      <text class="fab-icon">+</text>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { localServiceAPI } from '@/utils/api.js'
import CreditChecker from '@/utils/creditChecker.js'

// 响应式数据
const services = ref([])
const isLoading = ref(false)
const isRefreshing = ref(false)
const hasMore = ref(true)
const selectedStatus = ref('')

// 分页参数
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 状态选项
const statusOptions = [
  { label: '全部', value: '' },
  { label: '已上架', value: 'PUBLISHED' },
  { label: '待上架', value: 'DRAFT' },
  { label: '已下架', value: 'OFFLINE' }
]

// 统计数据状态
const stats = ref({
  total: 0,
  published: 0,
  draft: 0,
  offline: 0
})

// 计算属性
const totalCount = computed(() => stats.value.total)
const sellingCount = computed(() => stats.value.published)
const draftCount = computed(() => stats.value.draft)
const offlineCount = computed(() => stats.value.offline)

// 生命周期
onMounted(() => {
  loadMyServices()
})

// 页面显示时刷新数据（从其他页面返回时）
onShow(() => {
  // 刷新列表数据
  loadMyServices(true)
})

// 方法定义
const loadMyServices = async (isRefresh = false) => {
  if (isLoading.value) return
  
  try {
    isLoading.value = true
    
    if (isRefresh) {
      pagination.page = 1
      hasMore.value = true
    }
    
    // 构建查询参数
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      limit: pagination.pageSize
    }
    
    // 添加状态筛选
    if (selectedStatus.value) {
      params.status = selectedStatus.value
    }
    
    const response = await localServiceAPI.getMyServices(params)
    
    if (response.success) {
      const newServices = response.data?.items || []
      
      if (isRefresh) {
        services.value = newServices
      } else {
        // 使用去重逻辑避免重复数据
        const existingIds = new Set(services.value.map(item => item.id))
        const uniqueNewServices = newServices.filter(item => !existingIds.has(item.id))
        services.value = [...services.value, ...uniqueNewServices]
      }
      
      // 更新分页信息
      if (response.pagination) {
        pagination.total = response.pagination.total
        hasMore.value = pagination.page < response.pagination.totalPages
        
        // 更新统计数据（仅在第一页或刷新时）
        if (isRefresh || pagination.page === 1) {
          if (!selectedStatus.value) {
            stats.value.total = response.pagination.total
          }
        }
      } else {
        hasMore.value = newServices.length >= pagination.pageSize
      }
      
      // 实时计算当前已加载数据的统计
      updateLocalStats()
    }
    
  } catch (error) {
    console.error('获取我的服务失败:', error)
    uni.showToast({
      title: '获取我的发布失败',
      icon: 'none'
    })
  } finally {
    isLoading.value = false
    isRefreshing.value = false
  }
}

const loadMore = () => {
  if (!hasMore.value || isLoading.value) return
  
  pagination.page++
  loadMyServices()
}

const onRefresh = () => {
  isRefreshing.value = true
  loadMyServices(true)
}

// 更新本地统计数据
const updateLocalStats = () => {
  if (!selectedStatus.value) {
    // 没有筛选时，计算实际统计
    stats.value.published = services.value.filter(item => item.status === 'PUBLISHED').length
    stats.value.draft = services.value.filter(item => item.status === 'DRAFT').length
    stats.value.offline = services.value.filter(item => item.status === 'OFFLINE').length
    // 如果还没有总数，使用当前列表长度
    if (stats.value.total === 0) {
      stats.value.total = services.value.length
    }
  }
}

const changeStatus = (status) => {
  selectedStatus.value = status
  loadMyServices(true)
}

const goToDetail = (id) => {
  uni.navigateTo({
    url: `/pages/local-services/detail?id=${id}`
  })
}

// 工具方法
const getStatusClass = (status) => {
  const classMap = {
    'PUBLISHED': 'status-selling',
    'DRAFT': 'status-sold',
    'OFFLINE': 'status-offline'
  }
  return classMap[status] || 'status-default'
}

const getAuditStatusClass = (auditStatus) => {
  const classMap = {
    '待审核': 'audit-pending',
    'PENDING': 'audit-pending',
    '已通过': 'audit-approved',
    'APPROVED': 'audit-approved',
    '已拒绝': 'audit-rejected',
    'REJECTED': 'audit-rejected'
  }
  return classMap[auditStatus] || 'audit-default'
}

const getStatusText = (service) => {
  const statusMap = {
    'PUBLISHED': '已上架',
    'DRAFT': '待上架',
    'OFFLINE': '已下架'
  }
  return statusMap[service.status] || service.status
}

const getAuditStatusText = (auditStatus) => {
  const auditStatusMap = {
    'PENDING': '待审核',
    'APPROVED': '已通过',
    'REJECTED': '已拒绝'
  }
  return auditStatusMap[auditStatus] || auditStatus
}

const formatLocation = (item) => {
  const province = item.province || ''
  const city = item.city || ''

  if (!province && !city) {
    return '未填写'
  }

  if (province && city) {
    // 如果省份和城市相同（如北京市、上海市等直辖市），只显示一个
    if (province === city || city.includes(province.replace('市', '').replace('省', '').replace('自治区', ''))) {
      return province
    }
    return `${province} ${city}`
  }

  return province || city
}

const formatPrice = (price) => {
  if (!price) return '0'
  return Number(price).toLocaleString('zh-CN')
}

const formatTime = (timeStr) => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return `${year}年${month}月${day}日`
}


const offlineService = async (service) => {
  try {
    uni.showModal({
      title: '确认下架',
      content: `确定要下架此服务吗？`,
      success: async (res) => {
        if (res.confirm) {
          const response = await localServiceAPI.offlineService(service.id)
          
          if (response.success) {
            uni.showToast({
              title: '下架成功',
              icon: 'success'
            })
            
            // 更新本地数据
            const index = services.value.findIndex(item => item.id === service.id)
            if (index !== -1) {
              services.value[index].status = 'OFFLINE'
              // 更新统计数据
              updateLocalStats()
            }
          } else {
            uni.showToast({
              title: response.message || '下架失败',
              icon: 'none'
            })
          }
        }
      }
    })
  } catch (error) {
    console.error('下架服务失败:', error)
    uni.showToast({
      title: '下架失败',
      icon: 'none'
    })
  }
}

const republishService = async (service) => {
  try {
    uni.showModal({
      title: '确认重新上架',
      content: `确定要重新上架此服务吗？服务将在30分钟后自动上架。`,
      success: async (res) => {
        if (res.confirm) {
          const response = await localServiceAPI.republishService(service.id)
          
          if (response.success) {
            uni.showToast({
              title: '重新提交成功',
              icon: 'success'
            })
            
            // 更新本地数据
            const index = services.value.findIndex(item => item.id === service.id)
            if (index !== -1) {
              services.value[index] = response.data
              // 更新统计数据
              updateLocalStats()
            }
          } else {
            uni.showToast({
              title: response.message || '重新上架失败',
              icon: 'none'
            })
          }
        }
      }
    })
  } catch (error) {
    console.error('重新上架服务失败:', error)
    uni.showToast({
      title: '重新上架失败',
      icon: 'none'
    })
  }
}

const deleteService = async (service) => {
  try {
    uni.showModal({
      title: '确认删除',
      content: '删除后无法恢复，确定要删除这条服务信息吗？',
      success: async (res) => {
        if (res.confirm) {
          const response = await localServiceAPI.deleteService(service.id)
          
          if (response.success) {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            })
            
            // 从列表中移除
            const index = services.value.findIndex(item => item.id === service.id)
            if (index !== -1) {
              services.value.splice(index, 1)
              // 更新统计数据
              stats.value.total = Math.max(0, stats.value.total - 1)
              updateLocalStats()
            }
          } else {
            uni.showToast({
              title: response.message || '删除失败',
              icon: 'none'
            })
          }
        }
      }
    })
  } catch (error) {
    console.error('删除服务失败:', error)
    uni.showToast({
      title: '删除失败',
      icon: 'none'
    })
  }
}

const editService = (service) => {
  uni.navigateTo({
    url: `/pages/local-services/edit?id=${service.id}`
  })
}

const goToPublish = async () => {
  const hasCredit = await CreditChecker.checkLocalServiceCredit({
    fromPage: '/pages/local-services/publish',
    action: '发布本地服务'
  })
  if (!hasCredit) {
    return
  }
  uni.navigateTo({
    url: '/pages/local-services/publish'
  })
}
</script>

<style scoped>
.my-listings-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
  position: relative;
  overflow: hidden;
}

.header-stats {
  background: white;
  padding: 30rpx;
  display: flex;
  justify-content: space-around;
  border-bottom: 1rpx solid #eee;
}

.stat-item {
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  color: #22c55e;
  margin-bottom: 10rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #666;
}

.status-filter {
  background: white;
  padding: 0 30rpx;
  display: flex;
  border-bottom: 1rpx solid #eee;
}

.status-tab {
  flex: 1;
  text-align: center;
  padding: 30rpx 0;
  font-size: 28rpx;
  color: #666;
  border-bottom: 3rpx solid transparent;
}

.status-tab.active {
  color: #22c55e;
  border-bottom-color: #22c55e;
}

.listings-scroll {
  flex: 1;
  height: 0; /* 关键：让flex子元素能正确计算高度 */
  -webkit-overflow-scrolling: touch; /* iOS滚动优化 */
  overflow-y: auto; /* 确保可以滚动 */
}

.listings-list {
  padding: 20rpx;
  padding-bottom: 200rpx; /* 增加底部间距，避免被悬浮按钮遮挡 */
  min-height: 100%; /* 确保内容至少占满容器高度 */
}

.listing-item {
  background: white;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
}

.listing-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.company-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
}

.status-tags {
  display: flex;
  gap: 10rpx;
  align-items: center;
}

.status-tag {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 22rpx;
  color: white;
}

.status-selling {
  background: #22c55e;
}

.status-sold {
  background: #ef4444;
}

.status-offline {
  background: #6b7280;
}

.audit-tag {
  padding: 6rpx 12rpx;
  border-radius: 16rpx;
  font-size: 20rpx;
  color: white;
}

.audit-pending {
  background: #f59e0b;
}

.audit-approved {
  background: #10b981;
}

.audit-rejected {
  background: #ef4444;
}

.listing-info {
  margin-bottom: 20rpx;
}

.info-row {
  display: flex;
  margin-bottom: 10rpx;
  font-size: 26rpx;
}

.label {
  color: #666;
  width: 140rpx;
}

.value {
  color: #333;
  flex: 1;
}

.value.auto-publish {
  color: #f59e0b;
  font-weight: 500;
}

.value.audit-comment {
  color: #6b7280;
  font-style: italic;
}

.listing-footer {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.price-section {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.price {
  font-size: 30rpx;
  font-weight: bold;
  color: #ef4444;
}

.price.negotiable {
  color: #f59e0b;
}

.rejected-tip {
  font-size: 22rpx;
  color: #ef4444;
  margin-top: 6rpx;
  line-height: 1.2;
}

.action-buttons {
  display: flex;
  gap: 15rpx;
}

.action-btn {
  padding: 10rpx 20rpx;
  border: none;
  border-radius: 6rpx;
  font-size: 24rpx;
  color: white;
}

.edit-btn {
  background: #3b82f6;
}

.offline-btn {
  background: #6b7280;
}

.online-btn {
  background: #22c55e;
}

.sold-btn {
  background: #f59e0b;
}

.delete-btn {
  background: #ef4444;
}

.loading-section,
.no-more-section,
.empty-section {
  padding: 40rpx;
  text-align: center;
}

.loading-text,
.no-more-text,
.empty-text {
  font-size: 26rpx;
  color: #999;
  margin-bottom: 20rpx;
}

.publish-btn {
  padding: 20rpx 40rpx;
  background: #22c55e;
  color: white;
  border: none;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.fab {
  position: fixed;
  right: 40rpx;
  bottom: 40rpx;
  width: 120rpx;
  height: 120rpx;
  background: #22c55e;
  border-radius: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(34, 197, 94, 0.3);
  z-index: 999;
}

.fab-icon {
  font-size: 48rpx;
  color: white;
  font-weight: bold;
}
</style>
